'use strict'
const log = require('../../log.js')
/*
 * 这个页面是模板文件
*/

var ejs = require('ejs')  //引入ejs模板
var heredoc = require('heredoc')  //包裹模板文件
var crypto = require('crypto') // nodejs 自带不需要安装


var tpl = heredoc(function(){/*
<!DOCTYPE html>
<html>
	<head>
		<title>到件信息查询</title>
		<meta name = "viewport" content = "initial-scale=1, maximum-scale=1, minimum-sacle=1"
	</head>

	<body>
		<h1>点击表体，开始录音翻译</h1>
		<p id = "title"></p>
		<div id = "poster"></div>
		<script src = "http://www.zeptojs.cn/skin/zepto-docs.min.js"></script> <!-- 获取DOM -->
		<script src = "http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script> <!-- 官方jssdk 文件 -->
		<script>
			wx.config({
			    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			    appId: 'wx36e2283e00c8738e', // 必填，公众号的唯一标识
			    timestamp: '<%= timestamp %>', // 必填，生成签名的时间戳
			    nonceStr: '<%= noncestr %>', // 必填，生成签名的随机串
			    signature: '<%= signature %>',// 必填，签名，见附录1
			    jsApiList: [
					'startRecord',
					'stopRecord',
					'onVoiceRecordEnd',
					'translateVoice'
			    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
			});
		</script>
	</body>
</html>
*/})
var createNonce = function(){ //生成随机字符串
	return Math.random().toString(36).substr(2,15)
}
var createTimestamp = function(){	//生成时间戳
	return parseInt(new Date().getTime() / 1000, 10) + ''   
}
var _sign = function(noncestr, ticket, timestamp, url){
	var params = [
		'noncestr=' + noncestr,
		'jsapi_ticket=' + ticket,
		'timestamp=' + timestamp,
		'url=' + url
	]
	var str = params.sort().join('&')
// log.info(str)	
	var shasum = crypto.createHash('sha1')
	shasum.update(str)

	return shasum.digest('hex', )
}

function sign(ticket, url){
	var noncestr = createNonce()
	var timestamp = createTimestamp()
	var signature = _sign(noncestr, ticket, timestamp, url)

	return {
		noncestr: noncestr,
		timestamp: timestamp,
		signature: signature
	}
}

var wx = require('../../wx/index')

exports.daojian =async  function (ctx,next){
	// var wechatApi = new Wechat(config.wechat)
	var wechatApi = wx.getWechat()

	var data = await wechatApi.fetchAccessToken()
	var access_token = data.access_token

	var ticketData = await wechatApi.fetchTicket(access_token)
// log.info(access_token)
	var ticket = ticketData.ticket
	var url = ctx.href
	var params = sign(ticket, url)

	ctx.body = ejs.render(tpl, params) //ejs 引入模板文件

}
// exports.daojian = function(ctx, next){
// 	var wechatApi = wx.getWechat()
// 	return ctx.body = wechatApi
// }

